package com.wnnight.wys.filter;

import com.wnnight.wys.entity.StatusCode;
import com.wnnight.wys.exception.ValidateException;
import com.wnnight.wys.security.JwtToken;
import com.wnnight.wys.util.repairs.RepairsUtil;
import com.wnnight.wys.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtVerifyFilter extends AbstractAuthenticationProcessingFilter {
    public JwtVerifyFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try{
            attemptAuthentication((HttpServletRequest) request, (HttpServletResponse) response);
        }catch(ValidateException e){ //filter抛出的异常，在Spring之外，所以统一异常处理没办法
            response.getWriter().write(RepairsUtil.objectMapper.writeValueAsString(new ResultVo<>(StatusCode.TOKEN_FAIL)));
            response.getWriter().close();
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        log.debug("JwtVerifyFilter attemptAuthentication");
        String jwt = request.getHeader("jwt");
        log.debug("JWT:{}", jwt);
        JwtToken jwtToken = new JwtToken(jwt);
        return this.getAuthenticationManager().authenticate(jwtToken);
    }
}
